package com.xms.schema.service.relationship;

import com.xms.dependency.XmsDependencyException;
import com.xms.schema.entity.Attribute;
import com.xms.schema.event.AttributeDeletedEvent;
import com.xms.schema.extension.AttributeExt;
import com.xms.utils.CollectionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 字段删除后，级联删除关系
 * </p>
 *
 * @author migo
 * @since 2021/10/26
 */
@Service
public class RelationShipCascadeDeleter {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private IRelationShipDeleterService _relationShipDeleterService;

    @Autowired
    public void RelationShipCascadeDeleter(IRelationShipDeleterService relationShipDeleterService) {
        _relationShipDeleterService = relationShipDeleterService;
    }

    public boolean cascadeDelete(Attribute... parent) throws SQLException, XmsDependencyException {
        if (CollectionUtil.isEmpty(parent)) {
            return false;
        }
        List<UUID> ids = Arrays.stream(parent).filter(x -> AttributeExt.typeIsRef(x)).map(x -> x.getAttributeid()).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(ids)) {
            return false;
        }
        for (UUID id : ids) {
            _relationShipDeleterService.deleteByReferencingAttributeId(id);
        }
        return true;
    }

    @Async
    @EventListener
    public void onApplicationEvent(AttributeDeletedEvent event) throws XmsDependencyException, SQLException {
        logger.info("RelationShipCascadeDeleting");
        this.cascadeDelete(event.source);
    }
}
